package util

import (
	"time"

	"github.com/dgrijalva/jwt-go"
	"github.com/google/uuid"
	"golang.org/x/crypto/bcrypt"
)

var mySigningKey = []byte("jwt-secret")

type MyClaims struct {
	jwt.StandardClaims
	Username string `json:"username"`
}

func GetUUID() string {
	// 生成UUID并返回
	uuid := uuid.New().String()
	return uuid
}

func GetCurrentTime() string {
	// 获取当前时间并返回
	return time.Now().Format("2006-01-02 15:04:05")
}

// 密码加密
func HashPassword(password string) string {
	hashPassword, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
	if err != nil {
		return password
	}
	return string(hashPassword)
}

// 密码解密
func CheckPassword(password string, hashPassword string) bool {
	err := bcrypt.CompareHashAndPassword([]byte(hashPassword), []byte(password))
	return err == nil
}

// 生成token
func GenerateToken(username string) (string, error) {
	var claim = MyClaims{
		Username: username,
		StandardClaims: jwt.StandardClaims{
			Issuer: "admin",
		},
	}
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claim)
	tokenString, err := token.SignedString(mySigningKey)
	return tokenString, err
}

// 解析token
func ParseToken(tokenString string) string {
	token, err := jwt.ParseWithClaims(tokenString, &MyClaims{}, func(token *jwt.Token) (interface{}, error) {
		return mySigningKey, nil
	})
	if err != nil {
		return ""
	}
	var username string
	if claims, ok := token.Claims.(*MyClaims); ok && token.Valid {
		username = claims.Username
	}
	return username
}
